import axios from 'axios';

export class WxTokenSDK {
  private config: {
    appId: string;
    appSecret: string;
  };
  private baseUrl = 'https://api.weixin.qq.com/cgi-bin';
  private accessToken: string | null = null;
  private expiresTime: number = 0;

  constructor(config: { appId: string; appSecret: string }) {
    this.config = config;
  }

  /**
   * 获取接口调用凭据
   */
  async getAccessToken(forceRefresh = false): Promise<string> {
    const now = Date.now();
    if (!forceRefresh && this.accessToken && now < this.expiresTime) {
      return this.accessToken;
    }

    try {
      // 打印当前使用的 appid
      console.log('获取 access_token，使用的 appid:', this.config.appId);
      
      // 检查 appid 和 appSecret 是否为空
      if (!this.config.appId || this.config.appId === '') {
        console.error('错误：appId 为空！');
        throw new Error('appid missing');
      }
      
      if (!this.config.appSecret || this.config.appSecret === '') {
        console.error('错误：appSecret 为空！');
        throw new Error('appsecret missing');
      }
      
      const requestParams = {
        grant_type: 'client_credential',
        appid: this.config.appId,
        secret: this.config.appSecret
      };
      
      console.log('请求参数:', JSON.stringify(requestParams));
      
      const { data } = await axios.get(`${this.baseUrl}/token`, {
        params: requestParams
      });

      console.log('微信返回数据:', JSON.stringify(data));

      if (data.errcode) {
        throw new Error(`${data.errmsg} (${data.errcode})`);
      }

      this.accessToken = data.access_token;
      if (!this.accessToken) {
        throw new Error('access_token is empty');
      }
      this.expiresTime = now + (data.expires_in - 300) * 1000;
      return this.accessToken;
    } catch (error: any) {
      console.error('获取 access_token 失败:', error);
      throw new Error(`获取access_token失败: ${error.message}`);
    }
  }
} 